package P07_读写锁;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class P01_ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i < 5; i++) {
            int finalI = i + 1;
            new Thread(() -> {
                myCache.put(String.valueOf(finalI), String.valueOf(finalI));
            }, String.valueOf(i + 1)).start();
        }
        for (int i = 0; i < 5; i++) {
            int finalI = i + 1;
            new Thread(() -> {
                myCache.get(String.valueOf(finalI));
            }, String.valueOf(i + 1)).start();
        }
    }
}

class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 放数据
    public void put(String key, Object value) {
        // 添加写锁
        readWriteLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName() + "正在写入操作" + key);

        try {
            // 模拟写入延时
            TimeUnit.MICROSECONDS.sleep(300);

            // 放数据
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写完了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    // 取数据
    public Object get(String key) {
        // 添加读锁
        readWriteLock.readLock().lock();
        System.out.println(Thread.currentThread().getName() + "正在读取操作" + key);
        Object result = null;
        try {
            // 模拟写入延时
            TimeUnit.MICROSECONDS.sleep(300);
            System.out.println(Thread.currentThread().getName() + "取完了");
            result = map.get(key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
        return result;
    }
}
